use crate::sequence::ViewMarker;
use crate::view::Cx;
use crate::widget::ChangeFlags;
use crate::{id::Id, view::View};

pub struct Label {
    text: String,
    color: [f64; 4],
}

impl ViewMarker for Label {}

impl Label {
    pub fn new(text: String) -> Self {
        Self {
            text,
            color: [0.1, 0.2, 0.1, 1.0],
        }
    }

    pub fn with_color(mut self, color: [f64; 4]) -> Self {
        self.color = color;
        self
    }
}

impl<T> View<T> for Label {
    type State = ();

    type Element = crate::widget::Label;

    fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) {
        let (id, element) = cx.with_new_id(|cx| {
            crate::widget::Label::new(cx.id_path.clone(), self.text.clone(), self.color.clone())
        });
        (id, (), element)
    }

    fn rebuild(
        &self,
        prev: &Self,
        _cx: &mut Cx,
        _id: &mut Id,
        _state: &mut Self::State,
        element: &mut Self::Element,
    ) -> ChangeFlags {
        if self.text != prev.text {
            element.text = self.text.clone();
            ChangeFlags::PAINT | ChangeFlags::LAYOUT
        } else {
            ChangeFlags::empty()
        }
    }

    fn message(
        &self,
        _id_path: &[Id],
        _state: &mut Self::State,
        event: Box<dyn std::any::Any>,
        _app_state: &mut T,
    ) -> crate::message::EventResult<()> {
        crate::message::EventResult::Stale(event)
    }
}
